package Java基础.JUC同步工具;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Title A B C 线程交替顺序打印
 * @Author zhengqiang.tan
 * @Date 2021/6/19 9:42 AM
 *
 * A -0
 * B -0
 * C -0
 * A -1
 * B -1
 * C -1
 */
public class ABC {
    Lock lock = new ReentrantLock();
    Condition cA = lock.newCondition();
    Condition cB = lock.newCondition();
    Condition cC = lock.newCondition();

    public void execute(String flag) {
        lock.lock();

        try {
            for (int i = 0; i < 10; i++) {
                if (flag.equals("A")) {
                    System.out.println(Thread.currentThread().getName() + " -" + i);
                    cB.signal();
                    cA.await();
                }
                if ("B".equals(flag)) {
                    System.out.println(Thread.currentThread().getName() + " -" + i);
                    cC.signal();
                    cB.await();
                }
                if ("C".equals(flag)) {
                    System.out.println(Thread.currentThread().getName() + " -" + i);
                    cA.signal();
                    cC.await();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }


    public static void main(String[] args) {
        ABC abc = new ABC();
        new Thread(new Runnable() {
            @Override
            public void run() {
                abc.execute("A");
            }
        }, "A").start();

        new Thread(() -> {
            abc.execute("B");
        }, "B").start();

        new Thread(()->{
            abc.execute("C");
        },"C").start();
    }
}